package fragments;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;

import co.yeye.test.Constance;
import co.yeye.test.MainActivity;

/**
 * Created by yeye on 15/2/25.
 */
public class NetworkAlert {

    private setAlertDialog listener;
    private int networkState;
    private String[] choices = new String[]{"下次提醒","不再提醒"};
    private int choose=0;

    public NetworkAlert(final setAlertDialog listener , int networkState){
        this.listener=listener;
        this.networkState=networkState;
    }

    public void start(){
        // 检查是否需要通知
        final SharedPreferences sharedPreferences = MainActivity.getInstance().
                getSharedPreferences("MyOpto", Context.MODE_PRIVATE);
        if(networkState == Constance.NETWORK_VALID_GPRS) {
            if (sharedPreferences.getBoolean("networkAlert",true)) {
                AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.getInstance())
                        .setTitle("检测到当前网络环境为GPRS，继续使用将产生相关费用")
                        //.setMessage("检测到当前网络环境为GPRS，如继续使用将有可能产生相关费用，请确认继续使用。")
                        .setNegativeButton("不使用", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .setSingleChoiceItems(choices, 0, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                choose = i;
                            }
                        })
                        .setPositiveButton("继续", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (choose == 1) {
                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                    editor.putBoolean("networkAlert", false);
                                    editor.commit();
                                }
                                listener.execute();
                            }
                        })
                        .show();
            }
            // 不通知用户直接刷新
            else
                listener.execute();
        }
        // 在WIFI环境下直接刷新
        else if(networkState == Constance.NETWORK_VALID_WIFI)
            listener.execute();
    }

    public interface setAlertDialog{
        abstract void execute();
    }
}
